package com.cq.hd.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cq.hd.common.entity.GaoDeGeocode;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AliCloudApiUtils {

    private final static String HOST = "https://latlngto.market.alicloudapi.com";

    private final static String QUERY_LOCATION_PATH = "/lundroid/queryLocation";
    private final static String APP_CODE = "e3b23f7e0ab2480fb4736e0105431f3b";

    /**
     * 阿里云经纬度地址解析
     * @see "https://market.aliyun.com/products/57002002/cmapi00044642.html?spm=5176.2020520132.101.3.4d297218En5dZE#sku=yuncode3864200005"
     * @param longitude
     * @param latitude
     * @return
     */
    public static GaoDeGeocode queryLocation(String longitude, String latitude) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + APP_CODE);

        Map<String, String> querys = new HashMap<>();
        querys.put("lat", latitude);
        querys.put("lng", longitude);

        try {
            HttpResponse response = HttpUtils.doGet(HOST, QUERY_LOCATION_PATH, headers, querys);
            String resultStr = EntityUtils.toString(response.getEntity());

            log.info("ali_cloud_api.queryLocation-result:{}", resultStr);
            JSONObject result = JSON.parseObject(resultStr);

            JSONObject data = result.getJSONObject("data");
            if (data == null) {
                return null;
            }

            String country = data.getString("nation");
            String province = data.getString("province");
            String city = data.getString("city");
            String district = data.getString("district");
            String township = data.getString("street");
            String address = data.getString("address");
            if (province == null || city == null) {
                return null;
            }

            GaoDeGeocode gaoDeGeocode = new GaoDeGeocode();
            gaoDeGeocode.setFormattedAddress(address);
            gaoDeGeocode.setCountry(country);
            gaoDeGeocode.setProvince(province);
            gaoDeGeocode.setCity(city);
            gaoDeGeocode.setCountyName(district);
            gaoDeGeocode.setTownship(township);

            return gaoDeGeocode;
        } catch (Exception e) {
            log.error("阿里获取地理位置异常", e);
        }

        return null;
    }
}
